// controllers/userController.js
const user = require('../models/user');

function login(req, res) {
    const { loginName, password } = req.body;
    user.getUserByLoginName(loginName)
        .then(user => {
            if (user && user.password === password) {
                res.status(200).send({ message: 'Login successful' });
            } else {
                res.status(401).send({ message: 'Authentication failed' });
            }
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

function register(req, res) {
    const { loginName, password } = req.body;
    user.getUserByLoginName(loginName)
        .then(user => {
            if (user) {
                res.status(409).send({ message: 'User already exists' });
            } else {
                user.createUser(loginName, password)
                    .then(userId => {
                        res.status(201).send({ message: 'User created', userId });
                    })
                    .catch(err => {
                        res.status(500).send({ message: 'Server error' });
                    });
            }
        })
        .catch(err => {
            res.status(500).send({ message: 'Server error' });
        });
}

module.exports = {
    login,
    register
};